package top.healthylife.gateway.mgr.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.healthylife.basics.utils.utils.R;
import top.healthylife.gateway.mgr.model.ApiLog;
import top.healthylife.gateway.mgr.service.GatewayLogService;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * @author maoxiaomeng
 */
@Api(tags = "数据网关服务-接口日志信息")
@Slf4j
@RestController
@RequestMapping("/gateway/interface/chart")
@AllArgsConstructor
public class InterfaceLogChartController {

    GatewayLogService gatewayLogService;


    @ApiOperation("接口的调用统计折线图")
    @GetMapping("/invoke/count")
    public R<List<Map<String, Object>>> invokeCountChart(ApiLog.TimeSelect timeSelect) {
        String sql = "SELECT\n" +
                "\ttmp.day 'time', \n" +
                "\tcount( log.create_time ) 'count'\n" +
                "FROM\n" +
                "\tgateway_log AS log\n" +
                "\tRIGHT JOIN temp_day_time AS tmp ON \tDATE_FORMAT( log.create_time, '%Y-%m-%d' ) = tmp.day\n" +
                "\twhere tmp.day between '{}' and '{}' \n" +
                "GROUP BY\n" +
                "tmp.day\n" +
                "ORDER BY\n" +
                "tmp.day";
        LocalDate start = LocalDate.now();
        LocalDate end = start;
        switch (timeSelect) {
            case LAST_ONE_MONTH:
                start = start.withDayOfMonth(1);
                end = end.withDayOfMonth(end.lengthOfMonth());
                break;
            case LAST_THREE_MONTH:
                LocalDate localDate = start.minusMonths(2);
                start = localDate.withDayOfMonth(1);
                end = localDate.withDayOfMonth(localDate.lengthOfMonth());
            default:
                //ignore
        }
        String formatSql = StrUtil.format(sql, start.toString(), end.toString());
        return R.ok(gatewayLogService.query(formatSql));
    }




    @ApiOperation("任意sql执行")
    @GetMapping("/select")
    public R<List<Map<String, Object>>> queryLog(@RequestBody ApiLog.SqlInfo info) {
        String sqlBase = info.getSql();
        String sql = Base64.decodeStr(sqlBase);
        return R.ok(gatewayLogService.query(sql));
    }
}
